<template>
  <div ref="chartRef" :style="{
    width: ' 100 %',
    height: proxy.$size(height, '320px'),
  }">
  </div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, getCurrentInstance, onUnmounted } from 'vue';
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    data?: any;
    height?: string | number;
    seriesSet?: any;
  }>(),
  {
    data: [],
  },
);
// 获取 DOM 元素的引用
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    const _setData: any = {
      labelName: 'label',
      valueName: 'value',
      radius: ['60%', '96%'],
      ...props.seriesSet,
    }
    // 定义图表的配置项和数据
    const option = {
      //开启提示
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      //画图布局
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        top: '3%',
        containLabel: true
      },
      series: [
        {
          name: '',
          type: 'pie',
          radius: _setData.radius,
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: props.data.map((el: any) => ({
            name: el[_setData.labelName],
            value: el[_setData.valueName],
          }))
        }
      ],
    };
    // 使用配置项和数据显示图表
    option && chartInstance.setOption(option);
  }
  // 监听窗口大小变化并调整图表大小
  window.addEventListener('resize', handleResize);
});
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>
<style scoped lang="scss"></style>
